#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
void sort(int* a, int n)
{
	int* tem = new int[n];
	int gap = 1;
	while (gap <= n)
	{
		for (int i = 0; i < n; i += 2*gap)
		{
			int begin1 = i;
			int end1 = begin1 + gap - 1;
			int begin2 = begin1 + gap;
			int end2 = begin2 + gap - 1;

			if (begin2 >= n)
			{
				break;
			}
			if (end2 >= n)
			{
				end2 = n - 1;
			}
			int j = begin1;
			while (begin1 <= end1 && begin2 <= end2)
			{
				if (a[begin1] <= a[begin2])
				{
					tem[j++] = a[begin1++];
				}
				else
				{
					tem[j++] = a[begin2++];
				}
			}
			while (begin1 <= end1)
			{
				tem[j++] = a[begin1++];
			}
			while (begin2 <= end2)
			{
				tem[j++] = a[begin2++];
			}
			memcpy(a + i, tem + i, sizeof(int)*(end2 - i + 1));
		}
		gap *= 2;
	}
}

int main()
{
	int arr[] = { 21,3123,141,14,1523,532,46 };
	int len = sizeof(arr) / sizeof(int);
	for (int i = 0; i < len; i++)
	{
		cout << arr[i]<<" ";
	}
	cout << endl;
	sort(arr, len);
	for (int i = 0; i < len; i++)
	{
		cout << arr[i] << " ";
	}

	return 0;
}